<template>
  <div>
    <div>12121212</div>

    <el-upload
      class="avatar-uploader"
      action=""
      :show-file-list="false"
      :before-upload="beforeUploads"
      :http-request="doPut"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
  export default {
    name: "Upload",
    data() {
      return {
        imageUrl: ""
      }
    },
    methods: {
      beforeUploads(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      doPut(option) {
        let file = option.file
        let OSS = require('ali-oss');
        this.$post({
          url: "sts/sign"
        }).then(res => {
          let ossClient = new OSS({
            region: 'oss-cn-qingdao',
            accessKeyId: res.accessKeyId,
            accessKeySecret: res.accessKeySecret,
            stsToken: res.securityToken,
            bucket: 'lius-1'
          })
          ossClient.put("imgs/" + (new Date()).getTime() + ".jpg", file).then(res => {
            this.imageUrl = res.url
          })
        }).catch(err => {
          console.log(err)
        })
      }
    }
  }
</script>

<style scoped>
  .avatar-uploader .el-upload {
    cursor: pointer;
    position: relative;
    overflow: hidden;
    left: auto;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

</style>
